<template>
  <view class="content">
    <view class="header">
      <image :src="logoImg"></image>
    </view>

    <view class="list">
      <view class="list-call">
        <uni-easyinput class="sl-input" :inputBorder="false" prefixIcon="person-filled" v-model="login.Account"
          placeholderStyle="font-size: 15px;"
          :placeholder="`${$t('pages.sys.login.userName')}/${$t('pages.sys.login.email')}/${$t('pages.sys.login.mobile')}`" />
      </view>
      <view class="list-call">
        <uni-easyinput class="sl-input" :inputBorder="false" prefixIcon="locked-filled" type="password"
          v-model="login.Password" placeholderStyle="font-size: 15px"
          :placeholder="$t('pages.sys.login.passwordPlaceholder')" />
      </view>
    </view>

    <checkbox-group @change="handleRememberMeChange">
      <checkbox class="remember-me" value='remember' :checked="rememberMe === true">
        {{ $t('pages.sys.login.rememberMeText') }}
      </checkbox>
    </checkbox-group>

    <view class="button-login" hover-class="button-hover" @tap="handleLogin()">
      <text>{{$t('pages.sys.login.loginText')}}</text>
    </view>

    <view class="agreenment">
      <navigator url="/pages/sys/login/forgetPassword" open-type="navigate">
        {{ $t('pages.sys.login.forgetPasswordText') }}
      </navigator>
      <!-- 注：打包成APP后安卓5.1版本无法显示。安卓5.1版本上可直接使用 hasAuth + v-if 控制
			<Authority :value="'Root.Identity.Register'">
				<text>|</text>
				<navigator url="/pages/sys/login/register" open-type="navigate">{{ $t('pages.sys.login.signUpText') }}</navigator>
			</Authority> -->
      <text v-if="hasAuth('Root.Identity.Register')">|</text>
      <navigator v-if="hasAuth('Root.Identity.Register')" url="/pages/sys/login/register" open-type="navigate">
        {{ $t('pages.sys.login.signUpText') }}
      </navigator>
      <text>|</text>
      <navigator url="/pages/sys/login/setter" open-type="navigate">{{ $t('common.setText') }}</navigator>
    </view>

    <view>
      <!-- 提示信息弹窗 -->
      <uni-popup ref="message" type="message">
        <uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
      </uni-popup>
    </view>

    <view style="margin-top: 80rpx;" />
    <keyboard-listener @keydown="onKeydown" @keyup="onKeyup"></keyboard-listener>
  </view>
</template>

<script>
  import store from '@/store';
  import logoImg from '@/static/images/logos/logo.png';
  import {
    usePermission
  } from '@/utils/permission';
  import Authority from '@/components/authority/index.vue';
  import keyboardListener from '@/components/keyboard-listener/keyboard-listener';
  import {
    useScan
  } from "@/utils/scan-code";
  const {
    scan
  } = useScan();
  export default {
    components: {
      keyboardListener,
      Authority
    },
    data() {
      const {
        hasAuth
      } = usePermission();
      return {
        hasAuth,
        login: {
          GrantType: 'password',
          Account: '',
          Password: '',
          OrganizationId: '',
          ClientType: 3,
          ClientId: '',
          RefreshToken: '',
          VerifyCode: '',
          VerifyCodeId: '',
          mode: 'none', //不要默认的错误提示
        },
        rememberMe: false, // 记住我
        msgType: '',
        messageText: '',
        logoImg: logoImg
      };
    },
    computed: {},
    onShow() {
      const that = this;
      that.logoImg = store.getters.getLogo;
      // 导航栏多语言
      uni.setNavigationBarTitle({
        title: that.$t('pages.sys.login.loginText')
      });
      // 记住我
      that.rememberMe = that.$store.getters.getIdentityPersistent;
      // 监听扫描
      scan.start(async (res) => {
        // console.log('扫描结果', res);
        await that.scanHandler({
          data: res.data
        });
      });
    },
    onHide() {},
    destroyed: function() {
      // uni.showModal({
      //     title: 'destroyed',
      //     content: '停止监听扫描'
      // });
      // 页面退出时一定要停止监听扫描,否则监听将一直有效
      scan.stop();
    },
    onNavigationBarButtonTap(e) {
      const that = this;
      // console.log("点击了自定义按钮", e);
      if (e.index === 0) {
        uni.scanCode({
          success: async function(res) {
            // console.log('类型', res.scanType);
            // console.log('内容', res.result);
            await that.scanHandler({
              data: res.result
            });
          }
        });
      }
    },
    methods: {
      /** 处理记住我选项框值更改 */
      async handleRememberMeChange(e) {
        const that = this;
        // console.log('handleRememberMeChange', e);
        // console.log('handleRememberMeChange', e.detail.value);
        that.rememberMe = e.detail.value[0] === 'remember';
        await that.$store.dispatch('setIdentityPersistent', that.rememberMe);
      },
      /** 监听按键按下事件 */
      onKeydown(event) {
        // console.log('onKeydown', event);
        // uni.showModal({
        //     title: 'onKeydown',
        //     content: JSON.stringify(event)
        // });
      },
      /** 扫描处理器 */
      async scanHandler(res) {
        const that = this;
        const data = res.data;
        const tmpData = data.replace(/'/g, '"');
        const loginData = JSON.parse(tmpData);
        if (!loginData.Type || loginData.Type.toLowerCase() !== 'login') {
          uni.showModal({
            title: that.$t('scanCode.scanDataInvalid'),
            content: `${that.$t('scanCode.contentFormatShouldbe')} ${that.$t('scanCode.scanDataFormatLogin')}`,
            showCancel: false,
            confirmText: that.$t('common.okText')
          });
          return;
        }
        that.login.Account = loginData.Account;
        // that.login.Password = loginData.Password;
        // if(loginData.OrganizationId){
        // 	that.login.OrganizationId = loginData.OrganizationId;
        // }
        // 处理授权码登陆
        await that.handleAuthorizationLogin({
          /** 账号 */
          Account: loginData.Account,
          /** 授权码 */
          AuthCode: loginData.AuthCode,
          /** 组织机构编号 */
          OrganizationId: loginData.OrganizationId,
          /** 客户端类型 */
          ClientType: 3,
          /** 客户端ID，注：相同的用户身份、客户端ID只能同时登录一个，若不限制，该属性置空 */
          ClientId: null,

          /** 验证码 */
          VerifyCode: undefined,
          /** 验证码编号 */
          VerifyCodeId: undefined,
        });
      },
      /** 按键松开事件 */
      async onKeyup(event) {
        // console.log('onKeyup', event);
        // uni.showModal({
        //     title: 'onKeyup',
        //     content: JSON.stringify(event)
        // });
        const that = this;
        if (event.key.toUpperCase() === 'ENTER') {
          await that.handleLogin();
        } else if (event.key.toUpperCase() === 'F4') {
          //#ifdef APP-PLUS
          plus.runtime.quit(); // 退出APP
          //#endif
        }
      },
      /** 处理登陆 */
      async handleLogin() {
        const that = this;
        if (that.login.Account === undefined || that.login.Account === null || that.login.Account === '') {
          that.msgType = 'warn';
          that.messageText = that.$t('pages.sys.login.userNamePlaceholder');
          that.$refs.message.open();
          // uni.showToast({
          // 	icon: 'none',
          // 	title: that.$t('pages.sys.login.userNamePlaceholder')
          // });
          return;
        }
        if (that.login.Password === undefined || that.login.Password === null || that.login.Password === '') {
          that.msgType = 'warn';
          that.messageText = that.$t('pages.sys.login.passwordPlaceholder');
          that.$refs.message.open();
          // uni.showToast({
          // 	icon: 'none',
          // 	title: that.$t('pages.sys.login.passwordPlaceholder')
          // });
          return;
        }
        // console.log(that.$store);

        try {
          uni.showLoading({
            title: that.$t('common.loadingText'),
            mask: true
          });

          const userInfo = await that.$store.dispatch('login', {
            params: that.login,
            goHome: true,
            mode: 'modal'
          });
          // const userInfo = await that.$store.dispatch('login', { params: that.login, goHome: false, mode: 'modal' });
          // console.log('获取到用户了',userInfo);
          if (userInfo) {
            // 如果在这里设置主动跳转，那么上面的方法需要设置成：
            // const userInfo = await that.$store.dispatch('login', { params: that.login, goHome: false, mode: 'modal' });
            // const pages = getCurrentPages();
            // // console.log('loginPage', pages);
            // if(pages && pages.length > 1){
            // 	// 存在上级页面，直接返回
            // 	console.log('loginPage', '存在上级页面，直接返回');
            // 	uni.navigateBack();
            // } else {
            // 	// 不存在上级页面，跳转到主页
            // 	console.log('loginPage', '不存在上级页面，跳转到主页');
            // 	uni.switchTab({
            // 		url: '/pages/sys/home/index'
            // 	});
            // }
          }

          uni.hideLoading();
        } catch (err) {} finally {
          uni.hideLoading();
        }
      },
      /** 处理授权码登陆 */
      async handleAuthorizationLogin(dto) {
        const that = this;
        try {
          uni.showLoading({
            title: that.$t('common.loadingText'),
            mask: true
          });

          const userInfo = await that.$store.dispatch('authorizationLogin', {
            params: dto,
            goHome: true,
            mode: 'modal'
          });
          // console.log('获取到用户了',userInfo);
          if (userInfo) {
            // 如果在这里设置主动跳转，那么上面的方法需要设置成：
            // const userInfo = await that.$store.dispatch('login', { params: that.login, goHome: false, mode: 'modal' });
            // const pages = getCurrentPages();
            // // console.log('loginPage', pages);
            // if(pages && pages.length > 1){
            // 	// 存在上级页面，直接返回
            // 	console.log('loginPage', '存在上级页面，直接返回');
            // 	uni.navigateBack();
            // } else {
            // 	// 不存在上级页面，跳转到主页
            // 	console.log('loginPage', '不存在上级页面，跳转到主页');
            // 	uni.switchTab({
            // 		url: '/pages/sys/home/index'
            // 	});
            // }
          }

          uni.hideLoading();
        } catch (err) {} finally {
          uni.hideLoading();
        }
      }
    }
  }
</script>

<style>
  page {
    display: flex !important;
    align-items: center !important;
    flex-direction: column !important;
    justify-content: center !important;
  }

  .content {
    /* display: flex; */
    /* flex-direction: column; */
    /* justify-content: center; */
    width: 100vw;
    /* background-color: red; */
  }

  .header {
    width: 161rpx;
    height: 161rpx;
    border-radius: 50%;
    margin-top: 30rpx;
    margin-left: auto;
    margin-right: auto;
  }

  .header image {
    width: 161rpx;
    height: 161rpx;
    /* border-radius: 50%; */
  }

  .list {
    display: flex;
    flex-direction: column;
    padding-top: 50rpx;
    padding-left: 70rpx;
    padding-right: 70rpx;
  }

  .list-call {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;
    color: #333333;
    border-bottom: 0.5px solid #e2e2e2;
  }

  .list-call .sl-input {
    flex: 1;
    text-align: left;
    font-size: 32rpx;
    margin-left: 16rpx;
  }

  /deep/ .uni-easyinput__content {
    background-color: #f5f5f5 !important;
  }

  .remember-me {
    display: flex;
    align-items: center;
    /* justify-content: center; */
    height: 120rpx;
    padding-left: 100rpx;
    padding-right: 70rpx;
    font-size: 15px;
    color: #8f939c;
  }

  .remember-me:active {
    background-color: #f8f8f8;
  }

  .button-login {
    color: #FFFFFF;
    font-size: 35rpx;
    width: 500rpx;
    height: 100rpx;
    background: linear-gradient(-90deg, rgba(60, 156, 255, 1), rgba(60, 156, 255, 1));
    border-radius: 50rpx;
    line-height: 100rpx;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    margin-top: 30rpx;
  }

  .button-login:active {
    background: linear-gradient(-90deg, rgba(60, 156, 255, 0.5), rgba(60, 156, 255, 0.5));
  }

  .button-hover {
    background: linear-gradient(-90deg, rgba(60, 156, 255, 0.8), rgba(60, 156, 255, 0.8));
  }

  .agreenment {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    font-size: 30rpx;
    margin-top: 50rpx;
    color: #FFA800;
    text-align: center;
    height: 40rpx;
    line-height: 40rpx;
  }

  .agreenment text {
    font-size: 24rpx;
    margin-left: 15rpx;
    margin-right: 15rpx;
  }
</style>
